package com.cetcs.kmga.dataManager;

import com.cetc.cloud.kmga.util.DateUtils;
import com.cetcs.kmga.dataManager.util.*;
import com.google.common.collect.Lists;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import org.apache.commons.httpclient.util.DateParseException;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.junit.Test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

/**
 * 类注释
 *
 * @author xutao
 * @version V1.0 创建时间：2017-09-22 9:07
 *          Copyright 2017 by CETC
 */
public class TestHbase {

    @org.junit.Test
    public void testQuery() throws IOException {
        Table table = HBasePool.getInstance( ).getConnection( ).getTable(TableName.valueOf("KMGA:SDATA_AUDIT_DB_LOG_201709"));
        String rowKey = "00292233705300704338071000000299";
        Get get = new Get(rowKey.getBytes( ));
        Result ret = table.get(get);
//        for (Result result : scanner.next(10)) {
        Map<String, Object> params = result2Map(ret);
        params.forEach((k, v) -> {
            System.out.print(k + "==" + v);
            System.out.print(";");
        });

//        }
    }

    @Test
    public void testIp() {
        String ip = "121.1.1.4";
        long lo = IpUtil.getStringIpToLong(ip);
        System.out.println(lo + "====" + new String(IpUtil.getLongIpToString(lo)));
    }

    @org.junit.Test
    public void testPageQuery() throws IOException {


        byte[] columnNameArr = "OPER_TYPE".getBytes( );
        Filter filter = new SingleColumnValueFilter(columnNameArr, columnNameArr, CompareFilter.CompareOp.EQUAL,
                new SubstringComparator("10"));
        Filter opFilter = new SingleColumnValueFilter(columnNameArr, columnNameArr, CompareFilter.CompareOp.EQUAL,
                new SubstringComparator("11"));

//        List<Pair<byte[], byte[]>> fuzzyKeysData = Lists.newArrayList();
//        Filter frFilter = new FuzzyRowFilter(fuzzyKeysData);

        FilterList filterList = new FilterList( );
        filterList.addFilter(filter);
        filterList.addFilter(opFilter);
        FilterList newList = new FilterList(FilterList.Operator.MUST_PASS_ONE, filterList);
        HBasePageModel pd = new HBasePageModel(10000000);
        pd.setPageIndex(1);
        long max = Long.MAX_VALUE - DateUtils.getTodayBefore(7).getTime( );//起始
        long min = Long.MAX_VALUE - new Date( ).getTime( );//结束时间
        String endKey = "010" + max + "9999999999";
        String startKey = "010" + min + "1000000000";
        HBasePageModel pageModel = HBasePool.getInstance( ).scanResultByPageFilter("KMGA:SDATA_AUDIT_DB_LOG_201710", null, startKey.getBytes( ), endKey.getBytes( ), newList, 0, pd);
        List<Result> res = pageModel.getResultList( );
        int i = 0;
        System.out.println(pageModel.getQueryTotalCount( ));
        for (Result result : res) {
            Map<String, Object> map = result2Map(result);
            map.forEach((k, v) -> System.out.println("====" + k + "=====" + v + "---;"));
            System.out.println("=======第====" + i + "====次=========================");
        }
    }

    private Map<String, Object> result2Map(Result result) {
        Map<String, Object> ret = new HashMap<>( );
        if (result != null && result.listCells( ) != null) {
            String rowKey = "";
            for (Cell cell : result.listCells( )) {
                String key = Bytes.toString(CellUtil.cloneQualifier(cell));
                String value = Bytes.toString(CellUtil.cloneValue(cell));
                ret.put(key, value);
                rowKey = Bytes.toString(cell.getRowArray( ), cell.getRowOffset( ), cell.getRowLength( ));
            }

            ret.put("ROW_KEY", rowKey);
        }
        return ret;
    }

    @Test
    public void testH2DataBase() throws Exception {
        // 加载H2数据库驱动
        // 根据连接URL，用户名，密码获取数据库连接
        Connection conn = DruidH2Pool.getInstance( ).getConnection( );
        Statement stmt = conn.createStatement( );
        //如果存在USER_INFO表就先删除USER_INFO表
        stmt.execute("DROP TABLE IF EXISTS USER_INFO");
        //创建USER_INFO表
        stmt.execute("CREATE TABLE USER_INFO(id VARCHAR(36) PRIMARY KEY,name VARCHAR(100),sex VARCHAR(4))");
        //新增
        stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID( ) + "','大日如来','男')");
        stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID( ) + "','青龙','男')");
        stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID( ) + "','白虎','男')");
        stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID( ) + "','朱雀','女')");
        stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID( ) + "','玄武','男')");
        stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID( ) + "','苍狼','男')");
        //删除
        stmt.executeUpdate("DELETE FROM USER_INFO WHERE name='大日如来'");
        //修改
        stmt.executeUpdate("UPDATE USER_INFO SET name='孤傲苍狼' WHERE name='苍狼'");
        //查询
        ResultSet rs = stmt.executeQuery("SELECT * FROM USER_INFO");
        //遍历结果集
        while (rs.next( )) {
            System.out.println(rs.getString("id") + "," + rs.getString("name") + "," + rs.getString("sex"));
        }
        //释放资源
        stmt.close( );
        //关闭连接
        conn.close( );
    }

    @Test
    public void testH2ToolDataBase() throws Exception {
        String keyStr = "9223370526901299807100000002210000025210031000000210000002100000011121090106";
        System.out.println(keyStr.length( ));
    }

    private void createTestData() {
        //组装参数
        List<List<String>> columnArr = Lists.newArrayList( );
        List<String> singleParam = Lists.newArrayList( );
        singleParam.add("id");
        singleParam.add("36");
        columnArr.add(singleParam);
        singleParam = Lists.newArrayList( );
        singleParam.add("name");
        singleParam.add("100");
        columnArr.add(singleParam);
        singleParam = Lists.newArrayList( );
        singleParam.add("sex");
        singleParam.add("4");
        columnArr.add(singleParam);
        List<List<String>> data = Lists.newArrayList( );
        List<String> keyword = Lists.newArrayList( );
        keyword.add(UUID.randomUUID( ).toString( ));
        keyword.add("大日如来");
        keyword.add("男");
        data.add(keyword);
        keyword = Lists.newArrayList( );
        keyword.add(UUID.randomUUID( ).toString( ));
        keyword.add("猪大肠");
        keyword.add("女");
        data.add(keyword);
        String tbName = "USER_INFO";
        DruidH2Pool.getInstance( ).createCacheTb(tbName, columnArr);
    }

    @Test
    public void testFuzzyQuery() throws IOException, DateParseException {
        long startTimeL = DateUtils.getTodayBefore(5).getTime( );
        long endTimeL = new java.util.Date( ).getTime( );
        long max = Long.MAX_VALUE - startTimeL;//起始
        long min = Long.MAX_VALUE - endTimeL;//结束时间
        List<Pair<byte[], byte[]>> fuzzyKeysData = Lists.newArrayList( );
        Pair<byte[], byte[]> keyPair = getNewPair("96");
        fuzzyKeysData.add(keyPair);
        keyPair = getNewPair("56");
        fuzzyKeysData.add(keyPair);
        Filter rowFilter = new FuzzyRowFilter(fuzzyKeysData);
        String tbName = "KMGA:SDATA_AUDIT_DB_LOG_010_201711_INDEX";
        String starKey = String.valueOf(min);
        String endKey = String.valueOf(max);
        HBasePageModel ret = new HBasePageModel(1000000);
        FilterList filterList = new FilterList( );
        filterList.addFilter(rowFilter);
        ret = HBasePool.getInstance( ).
                scanResultByPageFilter(tbName, null, starKey.getBytes( ), endKey.
                        getBytes( ), filterList, 0, ret);
        List<Result> res = ret.getResultList( );
        int i = 0;
        System.out.println(ret.getQueryTotalCount( ));
        for (Result result : res) {
            i++;
            Map<String, Object> map = HBasePool.getInstance( ).result2Map(result);
            map.forEach((k, v) -> System.out.println("====" + k + "=====" + v + "---;"));
            System.out.println("=======第====" + i + "====次=========================");
        }
    }

    private Pair<byte[], byte[]> getPair(String rescId) {
        StringBuffer paramByteBuffer = new StringBuffer( );
        List<Byte> valByteList = Lists.newArrayList( );
        for (int i = 0; i < 19; i++) {
            paramByteBuffer.append("\\x00");
            byte valByte = 1;
            valByteList.add(valByte);
        }
        paramByteBuffer.append(rescId);
        for (int i = 0; i < 10; i++) {
            byte valByte = 0;
            valByteList.add(valByte);
        }
        paramByteBuffer.append("\\x00");
        byte valByte = 1;
        valByteList.add(valByte);
        String fPStr = paramByteBuffer.toString( );
        byte[] paramByteArr = Bytes.toBytesBinary(fPStr);
        byte[] valByteArr = new byte[valByteList.size( )];
        for (int i = 0; i < valByteList.size( ); i++) {
            valByteArr[i] = valByteList.get(i);
        }
        Pair<byte[], byte[]> keyPair = Pair.newPair(paramByteArr, valByteArr);
        return keyPair;
    }

    private Pair<byte[], byte[]> getNewPair(String rescId) {
        StringBuffer paramByteBuffer = new StringBuffer( );
        List<Byte> valByteList = Lists.newArrayList( );
        String keyStartStr = "922337052690129980710000000221000002521003100000021000000210000001112109";
        paramByteBuffer.append(keyStartStr);
        for (int i = 0; i < keyStartStr.length( ); i++) {
            byte valByte = 0;
            valByteList.add(valByte);
        }
        for (int i = 0; i < 2; i++) {
            paramByteBuffer.append("\\x00");
            byte valByte = 1;
            valByteList.add(valByte);
        }
        for (int i = 0; i < rescId.length( ); i++) {
            byte valByte = 0;
            valByteList.add(valByte);
        }
        paramByteBuffer.append(rescId);
        String fPStr = paramByteBuffer.toString( );
        byte[] paramByteArr = Bytes.toBytesBinary(fPStr);
        byte[] valByteArr = new byte[valByteList.size( )];
        for (int i = 0; i < valByteList.size( ); i++) {
            valByteArr[i] = valByteList.get(i);
        }
        Pair<byte[], byte[]> keyPair = Pair.newPair(paramByteArr, valByteArr);
        return keyPair;
    }

    @Test
    public void testPY() {
        Arrays.asList(Pinyin4jUtil.converterToFirstSpell("其他或已删除集群").split(",")).forEach(p -> System.out.println(p));
        System.out.println(Pinyin4jUtil.converterToFirstSpellOnly("其他或已删除集群").toUpperCase());

    }
}
